/*
 * @Descripttion: 
 * @version: 
 * @Author: Jun
 * @Date: 2021-05-27 15:41:37
 * @LastEditors: Jun
 * @LastEditTime: 2021-06-10 14:54:33
 */
import axios from "axios"
import Vue from 'vue';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import router from "@/router/index.js"
import { Loading } from 'element-ui';
import {baseURL} from "./common.js"

Vue.use(ElementUI);
let loadingInstance//loading实例化对象

const httpRequest = axios.create({
  baseURL: baseURL,
  timeout: 20000,
});

// 添加请求拦截器
httpRequest.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  loadingInstance = Loading.service();//显示loading

  let token = localStorage.getItem("zunyi_pc_token")

  if (token) {
    config.headers.jwttoken = token
  }

  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});

// 添加响应拦截器
httpRequest.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  switch (response.data.code) {
    case 1003:
      {
        ElementUI.Message.error(response.data.msg)
        router.replace("/login")
        break;
      }

    case 1005://未登录
      {
        ElementUI.Message.error(response.data.msg)
        router.replace("/login")
        break;
      }
    case 1006://刷新token
      {
        localStorage.setItem("zunyi_pc_token", response.data.data)//替换本地缓存里面的旧token

        let config = response.config
        config.headers.jwttoken = response.data.data//修改旧的请求头token
        return httpRequest.request(config)//重新发送请求
      }
    default:
      break;
  }
  loadingInstance.close()//关闭loading
  return response;
}, function (error) {
  // 对响应错误做点什么
  return Promise.reject(error);
});

export default httpRequest